/*
 * @Author: liaoxing
 * @Date: 2022-01-07 17:48:04
 * @LastEditors: liaoxing
 * @LastEditTime: 2022-01-24 14:56:53
 * @Description: liaoxing created
 * @FilePath: \品新集成管理系统\pin-xin-admin\src\utils\checkFormula.js
 */
let HtmlUtil = {
  /*1.用浏览器内部转换器实现html转码*/
  htmlEncode:function (html){
      let temp = document.createElement ("div");
      (temp.textContent != undefined ) ? (temp.textContent = html) : (temp.innerText = html);
      let output = temp.innerHTML;
      temp = null;
      return output;
  },
  /*2.用浏览器内部转换器实现html解码*/
  htmlDecode:function (text){
      let temp = document.createElement("div");
      temp.innerHTML = text;
      let output = temp.innerText || temp.textContent;
      temp = null;
      return output;
  }
}

const start = (value) => {
  const regex = new RegExp("[`~!#$^&*()=|{}':;',\\[\\]<>/?~！@#￥……&*（）——|{}【】‘；：”“'。，、？+-/]")
  for(let i = 0 ; i < value.length ; i++){
      let a = HtmlUtil.htmlEncode(value[i])
      if(regex.test(a)){       
        return true
      }
  }
}

const end = (value) => {
  let charArr = ['+', '-', '*', '/']
  for(let i = 0 ; i < charArr.length ; i++){
    if (value == charArr[i]) {
      return true
    }
  }
  return false
}

const variable = (value) => {
  if (!value) return '计算公式不能为空'
  let charArr = ['+', '-', '*', '/']
  for(let i = 0 ; i < charArr.length ; i++){
    if (value.indexOf(charArr[i]) > -1) {
      let reg = new RegExp('[' + charArr[i] + ']', "g")
      value = value.replace(reg, ")::")
    }
  }
  let valueArr = value.split(")::")
  for(let i = 0 ; i < valueArr.length ; i++){
    if (valueArr[i].indexOf(".") < 0) {
      return "公式格式错误,请检查!"
    }
  }
  return false
}

const addSpace = (value) => {
  let charArr = ['/', '+', '-', '*']
  for(let i = 0 ; i < charArr.length ; i++){
    if (value.indexOf(charArr[i]) > -1) {
      let reg = new RegExp('[' + charArr[i] + ']', "g")
      value = value.replace(reg, ' <span style="color: #1890ff">' + charArr[i] + '</span> ')
    }
  }
  return value
}

const getVariable = (value) => {
  const spaceReg = new RegExp("//s+", "g")
  value = value.replace(spaceReg, '')

  const sReg = new RegExp("[()（）]", "g")
  value = value.replace(sReg, '')

  const charArr = ['/', '+', '-', '*']
  for(let i = 0 ; i < charArr.length ; i++){
    if (value.indexOf(charArr[i]) > -1) {
      let reg = new RegExp('[' + charArr[i] + ']', "g")
      value = value.replace(reg, ':)')
    }
  }
  return value.split(":)")
}

const transformKey = (value, list) => {
  list.forEach(ele => {
    const reg = new RegExp(ele.title, "g")
    value = value.replace(reg, ele.key)
  })
  return value
}

export default {
  start,
  end,
  variable,
  addSpace,
  getVariable,
  transformKey
}
